home *** CD-ROM | disk | FTP | other *** search
- Listing 5 - member function definitions for a variable-length string
-
- //
- // str.cpp - a variable-length string (implementation)
- //
-
- #include <assert.h>
-
- #include "str.h"
-
- str::str(const char *s)
- {
- assert(s != 0);
- len = strlen(s);
- ptr = strcpy(new char[len + 1], s);
- }
-
- str::str(const str &s)
- {
- len = s.len;
- ptr = strcpy(new char[len + 1], s.ptr);
- }
-
- const str &str::operator=(const char *s)
- {
- assert(s != 0);
- size_t n = strlen(s);
- if (len != n)
- {
- delete [] ptr;
- len = n;
- ptr = new char[len + 1];
- }
- strcpy(ptr, s);
- return *this;
- }
-
- const str &str::operator=(const str &s)
- {
- if (this != &s)
- {
- if (len != s.len)
- {
- delete [] ptr;
- len = s.len;
- ptr = new char[len + 1];
- }
- strcpy(ptr, s.ptr);
- }
- return *this;
- }
-
- ostream &operator<<(ostream &s, const str &x)
- {
- return s << x.ptr;
- }
-
- istream &operator>>(istream &s, str &x)
- {
- char buf[512];
- s >> buf;
- x = buf;
- return s;
- }
-